<template>
  <div class="app-container">
    <el-dialog :title="title" :visible.sync="dialogPerFormVisible" width="70%">
      <el-form ref="dialogPerForm" :model="form" :inline="true" :rules="rules" class="demo-ruleForm" style="height: 300px;overflow: auto;">
        <el-tree
          ref="tree"
          node-key="id"
          default-expand-all="true"
          :props="perList.props"
          :data="perList.data"
          :current-node-key="perList.node"
          :default-checked-keys="perList.checked"
          class="filter-tree"
          show-checkbox
          :filter-node-method="filterNode"
          @node-click="nodeClick"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPerFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="FormPerSub('dialogPerForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="70%">
      <el-form ref="dialogForm" :model="form" :inline="true" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="11">
            <div class="grid-content bg-purple">
              <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
                <el-input v-model="form.name" autocomplete="off"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="11">
            <div class="grid-content bg-purple">
              <el-form-item label="排序" :label-width="formLabelWidth">
                <el-input-number v-model="form.sort" controls-position="right" :min="1" :max="10"></el-input-number>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="11">
            <div class="grid-content bg-purple">
                <el-form-item label="备注" :label-width="formLabelWidth">
                  <el-input v-model="form.description" autocomplete="off"></el-input>
                </el-form-item>
            </div>
          </el-col>
          <el-col :span="11">
            <div class="grid-content bg-purple">
              <el-form-item label="是否启用" :label-width="formLabelWidth">
                <el-radio-group v-model="form.isValid">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="FormSub('dialogForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-button-group style="margin: 0px 0px 10px 0px">
      <el-button type="primary" icon="el-icon-plus" @click="dialogForm(1)">添加</el-button>
      <el-button type="primary" icon="el-icon-edit" @click="dialogForm(2)">修改</el-button>
      <el-button type="primary" icon="el-icon-delete" @click="dialogDelete()">删除</el-button>
      <el-button type="primary" icon="el-icon-setting" @click="dialogPerForm">分配权限</el-button>
    </el-button-group>
    <el-container>
      <el-table
        :columns="columns"
        ref="singleTable"
        v-loading="listLoading"
        row-key="id"
        :height="height"
        :data="list"
        @row-click='rowClick'
        highlight-current-row
        element-loading-text="Loading"
        border
        fit
        default-expand-all
        :tree-props="{children: 'children'}">
        <el-table-column
           v-for="(column, key) in columns"
           :prop="column.prop"
           :label="column.label"
           :width="column.width"
           :fixed="column.fixed"
           :formatter="column.formatter">
        </el-table-column>
        <el-table-column
          prop="isValid"
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.isValid === '0' ? 'primary' : 'success'"
              disable-transitions>{{scope.row.isValid === '0'?'可用':'禁用'}}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-container>
    <el-pagination
          background
          :layout="layout"
          :total="total"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          @size-change="sizeChange"
          @current-change="currentChange"
        />
  </div>
</template>
<script>
import { parseTime } from '@/utils'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      columns: [],
      height: 200,
      winHeight: 200,
      title: '',
      value: [],
      options: [],
      dialogFormVisible: false,
      dialogPerFormVisible: false,
      layout: 'sizes, prev, pager, next, jumper, ->, total',
      pageSizes: [10, 20, 30, 40, 50, 100],
      pageSize: 10,
      total: 0,
      currentPage: 1,
      filterText: '',
      list: [],
      listLoading: true,
      formLabelWidth: '120px',
      row: [],
      perList: {
        node: '',
        checked: [],
        props: {
          id: 'id',
          label: 'name',
          children: 'children'
        },
        data: []
      },
      form: {
        id: '',
        addOrup: 1,
        sort: 1,
        name: '',
        isValid: '1',
        description: '',
        superMod: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created: function() {
    this.height = (window.innerHeight > 300 ? window.innerHeight - 200 : 100)
    this.getColumns()
    this.getPerList()
  },
  mounted() {
    // 挂载浏览器高度获取方法
    const that = this
    window.onresize = () => {
      return (() => {
        that.winHeight = window.innerHeight
      })()
    }
    // this.$refs.nav.style.height = this.winHeight + 'px'
  },
  watch: {
    // 监控浏览器高度变化
    winHeight(val) {
      this.winHeight = val
      this.height = (this.winHeight > 300 ? this.winHeight - 200 : 100)
    }
  },
  methods: {
    state(row, column) {
      return row.val === 0 ? '<el-tag type="success">可用</el-tag>' : '<el-tag type="success">禁用</el-tag>'
    },
    getColumns() {
      const self = this
      this.$http.get('/dev-api/columns/table/by/JSGL')
        .then(res => {
          self.columns = res.data.data
          self.getList()
        })
    },
    dialogDelete() {
      if (this.row.length <= 0) {
        alert('请先选择要删除的角色!')
        return
      }
      if (this.row.id === 'SYSTEMER') {
        alert('系统角色不能删除!')
        return
      }
      const self = this
      this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const that = this
        this.$http.get('/dev-api/role/del/' + this.row.id)
          .then(res => {
            that.$message({
              type: res.data.code === 20000 ? 'success' : 'info',
              message: res.data.code === 20000 ? '删除成功！' : '删除失败！'
            })
            self.getList()
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    dialogForm(val) {
      this.form.id = ''
      this.form.sort = 1
      this.form.name = ''
      this.form.description = ''
      this.form.isValid = '1'
      this.form.superMod = []
      if (val === 1) {
        this.title = '添加角色'
        this.form.sort = 1
        this.form.addOrup = 1
      } else {
        if (this.row.length <= 0) {
          alert('请先选择要修改的角色!')
          return
        }
        if (this.row.id === 'SYSTEMER') {
          alert('系统角色不能修改!')
          return
        }
        this.form.id = this.row.id
        this.form.sort = this.row.sort
        this.form.name = this.row.name
        this.form.isValid = this.row.isValid
        this.form.description = this.row.description
        this.title = '修改角色'
        this.form.addOrup = 2
      }
      this.dialogFormVisible = true
    },
    dialogPerForm(val) {
      this.title = '修改权限'
      if (this.row.length <= 0) {
        alert('请先选择要修改的权限!')
        return
      }
      if (this.row.id === 'SYSTEMER') {
        alert('系统角色不能修改!')
        return
      }
      if (this.row.pIdToString) {
        this.perList.checked = this.row.pIdToString.split(',')
      } else {
        this.perList.checked = []
      }
      this.dialogPerFormVisible = true
    },
    FormSub(formName) {
      const self = this
      if (this.form.addOrup === 1) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.form.superMod = this.value[this.value.length - 1 ]
            this.$http.post('/dev-api/role/save', this.form)
              .then(res => {
                this.dialogFormVisible = false
                self.$message({
                  type: res.data.code === 20000 ? 'success' : 'info',
                  message: res.data.code === 20000 ? '保存成功！' : '保存失败！'
                })
                self.getList()
              })
          }
        })
      } else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.form.superMod = this.value[this.value.length - 1 ]
            this.$http.post('/dev-api/role/update', this.form)
              .then(res => {
                console.log(res.data.code)
                this.dialogFormVisible = false
                self.$message({
                  type: res.data.code === 20000 ? 'success' : 'info',
                  message: res.data.code === 20000 ? '修改成功！' : '修改失败！'
                })
                self.getList()
                this.dialogFormVisible = false
              })
          }
        })
      }
    },
    FormPerSub(formName) {
      const self = this
      this.$refs[formName].validate((valid) => {
        this.$http.post('/dev-api/role/menu/update', {
          'roleId': this.row.id,
          'menuId': this.$refs.tree.getCheckedKeys().join(',')
        })
          .then(res => {
            this.dialogFormVisible = false
            self.$message({
              type: res.data.code === 20000 ? 'success' : 'info',
              message: res.data.code === 20000 ? '保存成功！' : '保存失败！'
            })
            self.getList()
            self.dialogPerFormVisible = false
          })
      })
    },
    getList: function() {
      var self = this
      this.$http.get('/dev-api/role/list?pageIndex=' + this.currentPage + '&pageSize=' + this.pageSize + '&parent=' + this.parent)
        .then(res => {
          self.list.pop()
          self.total = res.data.total
          self.list = res.data.data
          for (let i = 0; i < self.list.length; i++) {
            self.list[i].createTime = parseTime(self.list[i].createTime)
            self.list[i].modifyTime = parseTime(self.list[i].modifyTime)
            self.list[i].birthday = parseTime(self.list[i].birthday, '{y}-{m}-{d}')
          }
          self.listLoading = false
        })
    },
    getPerList: function() {
      const self = this
      this.$http.get('/dev-api/menu/list')
        .then(res => {
          self.perList.data = res.data.data
        })
    },
    currentChange(val) {
      this.currentPage = val
      this.fetchData(this.currentPage, this.pageSize)
    },
    sizeChange(val) {
      this.pageSize = val
      this.fetchData(this.currentPage, this.pageSize)
    },
    rowClick(row, column, event) {
      this.row = row
    },
    handleCheckAllChange(id, checked) {
      for (const item of this.perList.data) {
        if (item.id === id) {
          console.log(checked)
          if (checked) {
            console.log(item.checkAll)
            item.checkAll = true
          } else {
            console.log(item.checkAll)
            item.checkAll = false
          }
        }
      }
      this.perList.checkedPer = id ? this.perList.data : []
      // this.perList.isIndeterminate = false
    },
    handleClickAllChange(val) {
      console.log(val)
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.perList.data.length
      // this.perList.isIndeterminate = checkedCount > 0 && checkedCount < this.perList.data.length
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    nodeClick: function(row) {
      this.parent = row.id
    }
  }
}
</script>
